package cn.edu.sdjzu.xg.eagle.Controller;

import cn.edu.sdjzu.xg.eagle.Service.SchoolService;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/schoolCreate")
public class SchoolCreateCtl extends HttpServlet {

    private SchoolService schoolService;

    public void init() throws ServletException {
        try {
            // 获取service实例对象
            schoolService = ServiceFactory.getService(SchoolService.class,"SchoolService");
        } catch (BaseException e) {
            throw new ServletException("初始化SchoolService失败:" + e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        //设置请求字符编码
        request.setCharacterEncoding("utf-8");
        //设置响应字符编码
        response.setContentType("application/json;charset=utf-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();

        //根据 request 对象，获得的代表参数的 JSON 字串
        String school_json = JSONUtil.getJSON(request);

        // 处理请求为空的情况
        if (school_json == null) {
            message.put("message","未收到请求信息");
            response.getWriter().write(message.toJSONString());
            return;
        }

        try {
            //将JSON字串解析为School对象
            School schoolToAdd = JSON.parseObject(school_json, School.class);
            boolean isAdded = schoolService.addSchool(schoolToAdd);
            if (isAdded) {
                message.put("message","增加成功");
                message.put("code",200);
            } else {
                message.put("message","增加成功");
                message.put("code",500);
            }
        } catch (SQLException e) {
            message.put("message","数据库操作异常");
            message.put("code",500);
        } catch (Exception e) {
            message.put("message","网络异常");
            message.put("code",500);
        }

        response.getWriter().write(JSON.toJSONString(message));
    }


}
